package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.web.admin.properties.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

@EnableConfigurationProperties(value = MinioProperties.class)
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private MinioProperties minioProperties;
    @Override
    public String uploadFile(MultipartFile file) {
        try {
            //创建客户端对象
            MinioClient minioClient =
                    MinioClient.builder()
                            //设置Minio服务器的地址
                            .endpoint(minioProperties.getEndpoint())
                            //设置用户名和密码
                            .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                            .build();

            //判断star这个桶是否存在
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            if (!found) {
                //如果不存在则创建star桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            } else {
                System.out.println("Bucket "+minioProperties.getBucketName()+" already exists.");
            }

            //获取上传的文件的名字
            String filename = file.getOriginalFilename();
            //将当前日期进行格式化
            String format = DateFormatUtils.format(new Date(), "yyyy/MM/dd");
            //获取文件名的后缀
            String suffix = filename.substring(filename.lastIndexOf("."));
            //使用UUID随机生成一个字符串作为上传到Minio服务器的文件的名字
            String prefix = UUID.randomUUID().toString().replaceAll("-", "");
            //拼接新的文件名
            String newFileName = format+"/"+prefix+suffix;
            //获取输入流
            InputStream is = file.getInputStream();

            //创建PutObjectArgs对象
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    //设置桶的名字
                    .bucket(minioProperties.getBucketName())
                    //设置上传到Minio服务器之后文件的名字
                    .object(newFileName)
                    //设置输入流
                    .stream(is, is.available(), -1)
                    .build();
            //上传文件
            minioClient.putObject(putObjectArgs);

            //返回文件在mimio上的地址
            return minioProperties.getEndpoint()+"/"+minioProperties.getBucketName()+"/"+newFileName;

        } catch (Exception e) {
            System.out.println("Error occurred: " + e);
        }
        return null;
    }
}
